import { useEffect, useRef, useCallback } from "react";

// T extends (...args: any[]) => any:这是一个泛型类型约束，表示 T 必须是一个函数类型
function useThrottle<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 3000
): (...args: Parameters<T>) => void {
  const lastCalledTimeRef = useRef<number>(0);
  const throttledFunction = useRef<T>();

  // 使用 useCallback 缓存节流函数，避免每次渲染都生成新函数
  const throttleFn = useCallback(
    (...args: Parameters<T>) => {
      const now = Date.now();
      if (!lastCalledTimeRef.current || now - lastCalledTimeRef.current >= delay) {
        lastCalledTimeRef.current = now;
        throttledFunction.current = fn;
        fn(...args);
      }
    },
    [fn, delay]
  );

  // 使用 useEffect 清除 lastCalledTime，以便函数可以重新被调用
  useEffect(() => {
    return () => {
      lastCalledTimeRef.current = 0;
    };
  }, []);

  return throttleFn;
}

export default useThrottle;
